using System;
using System.Collections.Generic;
using System.Text;
using CodePlex.Resourceful.Amazon.S3;
using System.IO;

namespace CodePlex.Resourceful.CommandLine.Actions.S3
{
    public class PutObject : BaseS3
    {
        public PutObject() 
            : base("put-object", "Creates or updates a single S3 object.", 
                ParameterInfo.Required("aws-key","AWS access key ID",DefaultAwsKey()),
                ParameterInfo.Required("aws-secret","AWS secret key",DefaultAwsSecret()),
                ParameterInfo.Required("bucket","S3 bucket"),
                ParameterInfo.Required("file", "Local source file"),

                ParameterInfo.Optional("key","S3 destination key"),
                ParameterInfo.Optional("key-prefix","S3 destination key-prefix"),

                ParameterInfo.Optional("overwrite", string.Format("Whether or not to overwrite the object if it exists, one of: {0}", FormatEnumValues<OverwriteMode>()), FromEnum(OverwriteMode.Never)),
                ParameterInfo.Optional("create-bucket","Whether or not to create the bucket if it does not exist",false),
                ParameterInfo.Optional("location", "If creating bucket, which datacenter to use (US or EU)", Datacenter.US.ToString()),
                ParameterInfo.Optional("acl",string.Format("Canned acl policy, one of: {0}",Utils.Join(",",S3Constants.CannedAccessPolicies.All)),S3Constants.CannedAccessPolicies.Private)

            
            )
        {

        }


        protected override void GoS3(S3Connection connection, NameValuePairs parameters)
        {
           
                string bucket = parameters["bucket"];

                string file = parameters["file"];

                string key = parameters.GetIfExists("key");
                string keyPrefix = parameters.GetIfExists("key-prefix");

                OverwriteMode overwrite = GetOptional<OverwriteMode>(parameters, "overwrite");
                bool createBucket = GetOptional<bool>(parameters, "create-bucket");

                string acl = GetOptional<string>(parameters, "acl");
                Datacenter location = this.CheckLocation(GetOptional<string>(parameters, "location"));


                CheckFile(file);

                CheckAcl(acl);


                if (keyPrefix != null)
                {
                    key = keyPrefix + Path.GetFileName(file);
                }

                if (string.IsNullOrEmpty(key))
                {
                    key = Path.GetFileName(file);
                }


                this.CreateBucket(connection, createBucket, bucket, location);


                this.PutObject(connection, overwrite,bucket,key,acl,file);
           
        }

        

    }
}
